// src/stores/tabs.ts
import { defineStore } from 'pinia'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { ref } from 'vue'
import router from '@/router'

//定义好首页  
let indexRoute: TabItem = {
  fullPath: '/index',
  title: '首页',
  name: 'Index',
};


export interface TabItem {
  fullPath: string
  title: string
  name: string
}


export const useTabStore = defineStore('tab', () => {
  // 已打开的 Tab
  const tabs = ref<TabItem[]>([])
  //初始化首页进去
  tabs.value.push(indexRoute)
  // 当前激活的 Tab
  const activeTab = ref(indexRoute.fullPath)
  //当前激活的Tab的索引
  const activeTabIndex = ref(indexRoute.name)
  // 新增或切到已有
  function addTab(route: RouteLocationNormalizedLoaded) {
    const { fullPath, meta, name } = route
    const title = (meta?.title || route.name || '未命名') as string
    if (!tabs.value.some(t => t.fullPath === fullPath)) {
      tabs.value.push({ fullPath, title, name: name as string })
    }
    activeTab.value = fullPath
  }

  // 关闭单个
  function closeTab(fullPath: string) {
    const idx = tabs.value.findIndex(t => t.fullPath === fullPath)
    if (idx === -1) return

    tabs.value.splice(idx, 1)
    // 如果关的是当前页
    if (activeTab.value === fullPath) {
      const nextTab = tabs.value[idx - 1] || tabs.value[0]
      activeTab.value = nextTab ? nextTab.fullPath : indexRoute.fullPath
    }
  }

  // 关闭全部
  function closeAll() {
    tabs.value = [indexRoute]
    activeTab.value = indexRoute.fullPath
    activeTabIndex.value = indexRoute.name
    router.push(indexRoute.fullPath)
    localStorage.removeItem('activeTabIndex')

  }
  return { tabs, activeTab,activeTabIndex,addTab, closeTab, closeAll}
})